package com.hyhy.hycloud.commons.util.snowflake;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author lanpengfei
 * @date 2019-03-31
 */
public class IPSectionKeyGenerator {

    private static DefaultKeyGenerator defaultKeyGenerator;

    static {
        DefaultKeyGenerator.setWorkerId(initWorkerId());
        defaultKeyGenerator = new DefaultKeyGenerator();
    }

    private static long initWorkerId() {
        InetAddress address;
        try {
            address = InetAddress.getLocalHost();
        } catch (final UnknownHostException e) {
            throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!");
        }
        // 得到IP地址的byte[]形式值
        byte[] ipAddressByteArray = address.getAddress();
        long workerId = 0L;
        //如果是IPV4，计算方式是遍历byte[]，然后把每个IP段数值相加得到的结果就是workerId
        if (ipAddressByteArray.length == 4) {
            for (byte byteNum : ipAddressByteArray) {
                workerId += byteNum & 0xFF;
            }
            //如果是IPV6，计算方式是遍历byte[]，然后把每个IP段后6位（& 0B111111 就是得到后6位）数值相加得到的结果就是workerId
        } else if (ipAddressByteArray.length == 16) {
            for (byte byteNum : ipAddressByteArray) {
                workerId += byteNum & 0B111111;
            }
        } else {
            throw new IllegalStateException("Bad LocalHost InetAddress, please check your network!");
        }
        return workerId;
    }

    public static Number generateKey() {
        return defaultKeyGenerator.generateKey();
    }
}
